package org.example.domain.rebate.service;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.example.domain.rebate.event.SendRebateMessageEvent;
import org.example.domain.rebate.model.aggregate.BehaviorRebateAggregate;
import org.example.domain.rebate.model.entity.BehaviorEntity;
import org.example.domain.rebate.model.entity.BehaviorRebateOrderEntity;
import org.example.domain.rebate.model.valobj.BehaviorTypeVO;
import org.example.domain.rebate.model.valobj.DailyBehaviorRebateVO;
import org.example.domain.rebate.repository.IRebateRepository;
import org.example.domain.task.model.entity.TaskEntity;
import org.example.domain.task.model.valobj.TaskStateVO;
import org.example.types.common.Constants;
import org.example.types.enums.ResponseCode;
import org.example.types.event.BaseEvent;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BehaviorRebateService implements IBehaviorRebateService{

    @Resource
    private IRebateRepository rebateRepository;

    /**
     * 行为返利
     * 保存返利记录至数据库
     * 保存任务流水记录
     * 发送mq消息
     * @param behaviorEntity 包含用户id,行为类型,业务id
     * @return 订单号列表: 行为可能产生多种返利订单
     */
    @Override
    public List<String> createOrder(BehaviorEntity behaviorEntity) {
        BehaviorTypeVO behaviorTypeVO = behaviorEntity.getBehaviorTypeVO();
        String outBusinessNo = behaviorEntity.getOutBusinessNo();
        String userId = behaviorEntity.getUserId();

        //1.校验字段
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(outBusinessNo) || behaviorTypeVO == null){
            throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(),ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        //2.查询数据库配置,会有多个,因为一次行为可能有多个种类的返利
         List<DailyBehaviorRebateVO> dailyBehaviorRebateVOS = rebateRepository.queryDailyBehaviorRebatesByType(behaviorTypeVO);

        //3.构建聚合对象列表
         List<BehaviorRebateAggregate> behaviorRebateAggregates = new ArrayList<>();
         //构建订单id集合,将生成的订单id存起来返给前台
        List<String> orderIds = new ArrayList<>();
        // 3.1为每个配置生成订单
        for (DailyBehaviorRebateVO dailyBehaviorRebateVO : dailyBehaviorRebateVOS){
            String bizId = behaviorEntity.getUserId() + Constants.UNDERLINE + dailyBehaviorRebateVO.getRebateType() + Constants.UNDERLINE + behaviorEntity.getOutBusinessNo();
            BehaviorRebateOrderEntity behaviorRebateOrderEntity = BehaviorRebateOrderEntity.builder()
                    .rebateType(dailyBehaviorRebateVO.getRebateType())
                    .rebateDesc(dailyBehaviorRebateVO.getRebateDesc())
                    .behaviorType(dailyBehaviorRebateVO.getBehaviorType())
                    .rebateConfig(dailyBehaviorRebateVO.getRebateConfig())
                    .outBusinessNo(behaviorEntity.getOutBusinessNo())
                    .bizId(bizId)
                    .orderId(RandomStringUtils.randomNumeric(12))
                    .userId(userId)
                    .build();

            orderIds.add(behaviorRebateOrderEntity.getOrderId());

            //3.2.生成消息
            SendRebateMessageEvent.RebateMessage rebateMessage = SendRebateMessageEvent.RebateMessage.builder()
                    .userId(userId)
                    .bizId(bizId)
                    .rebateType(dailyBehaviorRebateVO.getRebateType())
                    .rebateDesc(dailyBehaviorRebateVO.getRebateDesc())
                    .rebateConfig(dailyBehaviorRebateVO.getRebateConfig())
                    .build();

            SendRebateMessageEvent sendRebateMessageEvent = new SendRebateMessageEvent();
            BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage> eventMessage =  sendRebateMessageEvent.buildEventMessage(rebateMessage);

            //3.3生成任务对象
            TaskEntity taskEntity = TaskEntity.builder()
                    .topic(sendRebateMessageEvent.topic())
                    .messageId(eventMessage.getId())
                    .message(JSON.toJSONString(eventMessage))
                    .state(TaskStateVO.create)
                    .userId(userId)
                    .build();

            //3.4添加聚合对象
            behaviorRebateAggregates.add(BehaviorRebateAggregate.builder()
                            .behaviorRebateOrderEntity(behaviorRebateOrderEntity)
                            .taskEntity(taskEntity)
                            .userId(userId)
                    .build());
        }

        //6.保存订单和task到数据库,包含发送mq消息
        rebateRepository.saveRebateRecord(behaviorRebateAggregates);

        return orderIds;
    }

    @Override
    public List<BehaviorRebateOrderEntity> queryRebateOrderByOutBusinessNo(String userId, String outBusinessNo) {

        return rebateRepository.queryRebateOrderByOutBusinessNo(userId,outBusinessNo);
    }
}
